package com.shine.minepressure.ui.resultinput;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.shine.minepressure.BR;
import com.shine.minepressure.R;
import com.shine.minepressure.app.Constants;
import com.shine.minepressure.base.BaseActivity;
import com.shine.minepressure.bean.BatchNumBean;
import com.shine.minepressure.bean.PackListBean;
import com.shine.minepressure.databinding.ActivityBaseBinding;
import com.shine.minepressure.databinding.ActivityResultInputBinding;
import com.shine.minepressure.http.ApiException;
import com.shine.minepressure.http.ECObserverString;
import com.shine.minepressure.http.RetrofitClient;
import com.shine.minepressure.http.RxUtils;
import com.shine.minepressure.http.Service;
import com.shine.minepressure.ui.adapter.PackageCheckAdapter;
import com.shine.minepressure.utils.SPUtils;
import com.shine.minepressure.view.pop.CommonListBottomPopup;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener;

public class ResultInputActivity extends BaseActivity<ActivityResultInputBinding, ResultInputViewModel> {
    private PackageCheckAdapter packageCheckAdapter;
    private String packList = "";
    private List<String> batchList = new ArrayList<>();

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_result_input;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ResultInputViewModel initViewModel() {
        return new ResultInputViewModel(this);
    }

    @Override
    public int appTheme() {
        return Constants.THEME_FULL;
    }

    @Override
    public void initData() {
        super.initData();
        setStatusBar();
        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

        packageCheckAdapter = new PackageCheckAdapter(binding.recyclerView);
        binding.recyclerView.setAdapter(packageCheckAdapter);

        packageCheckAdapter.setOnRVItemClickListener(new BGAOnRVItemClickListener() {
            @Override
            public void onRVItemClick(ViewGroup parent, View itemView, int position) {
                packageCheckAdapter.getData().get(position).setSelect(!packageCheckAdapter.getData().get(position).isSelect());
                packageCheckAdapter.notifyDataSetChanged();

                int count = 0;
                packList = "";
                for (PackListBean.PackListDTO baseBean : packageCheckAdapter.getData()) {
                    if (baseBean.isSelect()) {
                        count++;
                        packList = packList + baseBean.getPackName() + ";";
                    }
                }
                binding.chooseNum.setText("已选择" + count + "条");
            }
        });

        binding.back.setOnClickListener(this);
        binding.submit.setOnClickListener(this);
        binding.searchText.setOnClickListener(this);

        getPackList();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.submit:
                if (binding.searchText.getText().toString().equals("批次选择")) {
                    ToastMessage("请选择批次");
                    return;
                }
                if (binding.structure.getText().toString().isEmpty()) {
                    ToastMessage("请输入外观结构检测描述");
                    return;
                }
                if (TextUtils.isEmpty(packList)) {
                    ToastMessage("请选择包装检查");
                    return;
                }
                packList = packList.substring(0, packList.length() - 1);
                inputtingResult();
                break;
            case R.id.searchText:
                if (batchList.isEmpty()) {
                    getBatchNum(true);
                }

                CommonListBottomPopup commonListBottomPopup = new CommonListBottomPopup(this, batchList);
                new XPopup.Builder(this)
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .enableDrag(true)
                        .isDestroyOnDismiss(true)
                        .maxHeight(200)
                        .asCustom(commonListBottomPopup)/*.enableDrag(false)*/
                        .show();
                commonListBottomPopup.setListener(new CommonListBottomPopup.OnPopItemClickListener() {
                    @Override
                    public void onPopItemClick(View view, int position) {
                        binding.searchText.setText(batchList.get(position));
                        commonListBottomPopup.dismiss();
                    }
                });

                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                default:
                    break;
            }
        }
    }


    /**
     * 批次列表
     */
    private void getBatchNum(boolean showLoading) {
        if (showLoading)
            showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .GetBatchNum(null, null)
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserverString<String>() {
                    @Override
                    protected void _onNext(String str) {
                        dismissLoading();
                        BatchNumBean batchNumBean = new Gson().fromJson(str, BatchNumBean.class);

                        batchList.clear();
                        for (BatchNumBean.HistoryInspectionBatchDTO batchDTO : batchNumBean.getHistoryInspectionBatch()) {
                            batchList.add(batchDTO.getBatchNum());
                        }
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    /**
     * 获取包装列表信息
     */
    private void getPackList() {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .GetPackList()
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserverString<String>() {
                    @Override
                    protected void _onNext(String str) {
//                        dismissLoading();
                        getBatchNum(false);
                        PackListBean packListBean = new Gson().fromJson(str, PackListBean.class);
                        packageCheckAdapter.setData(packListBean.getPackList());
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    private void inputtingResult() {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .InputtingResult(null, null, binding.searchText.getText().toString(),
                        SPUtils.getInstance().getString(Constants.SP_LOGIN_NAME),
                        SPUtils.getInstance().getString(Constants.SP_LOGIN_USER_ID),
                        binding.structure.getText().toString(), packList)
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserverString<String>() {
                    @Override
                    protected void _onNext(String str) {
                        dismissLoading();
                        if (str.equals("true")) {
                            ToastMessage("提交成功");
                            finish();
                        }
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

}
